#include "led_driver.h"
#include <Arduino.h>
#include <driver/rmt.h>
#include <soc/rmt_reg.h>

// 优化后的常量定义
#define RMT_CLK_DIV 1  
#define RMT_TICK_NS (1000000000.0 / (80000000 / RMT_CLK_DIV)) // 每tick的纳秒数 (12.5ns)

// WS2812时序参数（纳秒）
#define T0H_NS 350    // 0码高电平时间 (0.35us)
#define T1H_NS 700    // 1码高电平时间 (0.7us)
#define T0L_NS 800    // 0码低电平时间 (0.8us)
#define T1L_NS 600    // 1码低电平时间 (0.6us)
#define RESET_US 50   // 复位时间(微秒)

// 预计算RMT周期数（使用固定值确保准确性）
#define T0H_CYCLES 28  // 0.35us / 12.5ns = 28
#define T1H_CYCLES 56  // 0.7us / 12.5ns = 56
#define T0L_CYCLES 64  // 0.8us / 12.5ns = 64
#define T1L_CYCLES 48  // 0.6us / 12.5ns = 48


// 验证计算结果
// T0H_CYCLES = 28 * 12.5ns = 350ns
// T1H_CYCLES = 56 * 12.5ns = 700ns
// T0L_CYCLES = 64 * 12.5ns = 800ns
// T1L_CYCLES = 48 * 12.5ns = 600ns

// 静态分配RMT项数组，避免动态内存分配
static rmt_item32_t rmtItems[LED_COUNT * 24 + 1]; // +1 for reset

LEDDriver::LEDDriver() {
    ledBuffer = new RGB[LED_COUNT];
    memset(ledBuffer, 0, sizeof(RGB) * LED_COUNT);
}

LEDDriver::~LEDDriver() {
    delete[] ledBuffer;
}

void LEDDriver::init() {
    // 初始化RMT
    rmt_config_t config = RMT_DEFAULT_CONFIG_TX((gpio_num_t)LED_PIN, RMT_CHANNEL);
    config.clk_div = RMT_CLK_DIV;
    //config.mem_block_num = RMT_MEM_NUM;
    config.mem_block_num = 1;   // 固定为1
    // 验证时序精度
    #ifdef DEBUG
    Serial.printf("RMT Tick: %.2f ns\n", RMT_TICK_NS);
    Serial.printf("T0H: %d cycles (target: %d ns, actual: %.2f ns)\n", 
                  T0H_CYCLES, T0H_NS, T0H_CYCLES * RMT_TICK_NS);
    Serial.printf("T1H: %d cycles (target: %d ns, actual: %.2f ns)\n", 
                  T1H_CYCLES, T1H_NS, T1H_CYCLES * RMT_TICK_NS);
    Serial.printf("T0L: %d cycles (target: %d ns, actual: %.2f ns)\n", 
                  T0L_CYCLES, T0L_NS, T0L_CYCLES * RMT_TICK_NS);
    Serial.printf("T1L: %d cycles (target: %d ns, actual: %.2f ns)\n", 
                  T1L_CYCLES, T1L_NS, T1L_CYCLES * RMT_TICK_NS);
    Serial.printf("Total 0 bit time: %.2f ns\n", (T0H_CYCLES + T0L_CYCLES) * RMT_TICK_NS);
    Serial.printf("Total 1 bit time: %.2f ns\n", (T1H_CYCLES + T1L_CYCLES) * RMT_TICK_NS);
    #endif
    
    ESP_ERROR_CHECK(rmt_config(&config));
    ESP_ERROR_CHECK(rmt_driver_install(config.channel, 0, 0));
}

void LEDDriver::setPixel(uint32_t index, uint8_t r, uint8_t g, uint8_t b) {
    if (index < LED_COUNT) {
        ledBuffer[index].r = r;
        ledBuffer[index].g = g;
        ledBuffer[index].b = b;
    }
}

void LEDDriver::setAllPixels(uint8_t r, uint8_t g, uint8_t b) {
    for (int i = 0; i < LED_COUNT; i++) {
        ledBuffer[i].r = r;
        ledBuffer[i].g = g;
        ledBuffer[i].b = b;
    }
}

void LEDDriver::show() {
    sendLEDData();
}

void LEDDriver::clear() {
    memset(ledBuffer, 0, sizeof(RGB) * LED_COUNT);
    show();
}

void LEDDriver::sendLEDData() {
    int itemIndex = 0;
    
    // 为每个LED生成RMT项
    for (int i = 0; i < LED_COUNT; i++) {
        // WS2812使用GRB顺序
        uint32_t color = (ledBuffer[i].g << 16) | (ledBuffer[i].r << 8) | ledBuffer[i].b;
        
        for (int j = 23; j >= 0; j--) {
            if (color & (1 << j)) {
                // 发送1码
                rmtItems[itemIndex].duration0 = T1H_CYCLES;
                rmtItems[itemIndex].duration1 = T1L_CYCLES;
            } else {
                // 发送0码
                rmtItems[itemIndex].duration0 = T0H_CYCLES;
                rmtItems[itemIndex].duration1 = T0L_CYCLES;
            }
            rmtItems[itemIndex].level0 = 1;
            rmtItems[itemIndex].level1 = 0;
            itemIndex++;
        }
    }
    
    // 添加复位信号（低电平）
    rmtItems[itemIndex].level0 = 0;
    rmtItems[itemIndex].level1 = 0;
    rmtItems[itemIndex].duration0 = (RESET_US * 1000 + RMT_TICK_NS/2) / RMT_TICK_NS; // 转换为周期数，四舍五入
    rmtItems[itemIndex].duration1 = 0;
    itemIndex++;
    
    // 发送RMT数据
    ESP_ERROR_CHECK(rmt_write_items(RMT_CHANNEL, rmtItems, itemIndex, true));
}

